# -*- coding: utf-8 -*-

from sklearn.feature_extraction import DictVectorizer #用来转化为整型数据
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
#sklearn对数据的处理格式是

allElectronicsdata = open(r'/Users/wangjunjie/Documents/projects/python_projects/1.csv','rb')
reader = csv.reader(allElectronicsdata) #按行读取表格中的内容
headers = reader.next() #得到头部信息

print(headers)

featureList = []
labelList = [

f]or row in reader:

    labelList.append(row[len(row) - 1])
    rowDict = {}

    for i in range(1,len(row) - 1 ):

        rowDict[headers[i]] = row[i]

    featureList.append(rowDict)

print(featureList)

vec = DictVectorizer();
dummyX = vec.fit_transform(featureList).toarray()
print("dunmmyX:"+ str(dummyX))
print (vec.get_feature_names())

print("labelList"+str(labelList))

#vectorize class labels
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print ("dummyY"+str(dummyY))

#using decision tree for classification

#clf = tree.DecisionTreeClassifier()
clf = tree.DecisionTreeClassifier(criterion='entropy') #申明创建一个Classifier
#http://scikit-learn.org/stable/modules/tree.html 分离器帮助文档
clf = clf.fit(dummyX,dummyY) #建模
print("clf: " + str(clf))

#Visulize model
with open("/Users/wangjunjie/Documents/projects/python_projects/allElectronicsInformationGainori.dot",'w') as f:
    f = tree.export_graphviz(clf,feature_names=vec.get_feature_names(),out_file = f)

oneRowX = dummyX[0,:]
print("oneRowX: "+ str(oneRowX))

newRowX = oneRowX

newRowX[0] = 1
newRowX[2] = 0

print("newRowX: "+ str(newRowX))

predictedY = clf.predict(newRowX)

print("predictedY: "+ str(predictedY))
